package cn.acewill.yxd.yunxundian.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.jimmy.common.util.ToastUtils;
import com.xiao.nicevideoplayer.NiceVideoPlayer;
import com.xiao.nicevideoplayer.TxVideoPlayerController;
import com.zyf.vc.ui.PlayVideoActiviy;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.model.ChongFuKouFen;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.reportViewBean;
import cn.acewill.yxd.yunxundian.model.tempLostRR;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.sign.PreViewAcitivity;
import cn.acewill.yxd.yunxundian.ui.user.ImageViewPagerActivity;
import cn.acewill.yxd.yunxundian.ui.user.ToolVideoPlayActivity;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;

/**
 * Created by xxx on 2018/2/1.
 */

public class PreviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

    private static final int ITEM_TYPE_HEADER = 0;
    private static final int ITEM_TYPE_CONTENT = 1;
    private static final int ITEM_TYPE_BOTTOM = 2;

    private int HEAD_COUNT = 1;
    private int FOOT_COUNT = 1;

    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());

    private List<reportViewBean> reportList;
    private List<reportViewBean.ZhutiBean> zhutiList;
    private Context mContext;
    private List<Employee> empList = new ArrayList<>();
    private String areaName = "----";
    private List<ChongFuKouFen> chongFuKouFens;


    public PreviewAdapter(Context context, List<reportViewBean> reportList){
        this.mContext = context;
        this.reportList = reportList;
        zhutiList = reportList.get(0).getZhuti();
        //zhuti 根据小项的id进行一次重组
        if (zhutiList!=null&&zhutiList.size()>0){

            Collections.sort(zhutiList, new Comparator<reportViewBean.ZhutiBean>() {
                @Override
                public int compare(reportViewBean.ZhutiBean o1, reportViewBean.ZhutiBean o2) {
                    //orderValue 排序
                    if (o1.getOrderValue()>o2.getOrderValue()){
                        return 1;
                    }
                    if (o1.getOrderValue() == o2.getOrderValue()){
                        return 0;
                    }
                    return -1;
                }
            });
        }
    }

    //行动计划人
    public void setEmpList( List<Employee> empList){
        this.empList = empList;
        notifyDataSetChanged();
    }
    //地区名称
    public void setAreaName(String areaName){
        this.areaName = areaName;
        notifyDataSetChanged();
    }
    //重复失分项
    public void setChongFu(List<ChongFuKouFen> kouFens){
        this.chongFuKouFens = kouFens;
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView=null;
        if (viewType == ITEM_TYPE_HEADER){
             itemView = LayoutInflater.from(mContext).inflate(R.layout.preview_head_view,parent,false);
             return new HeadViewHolder(itemView);
        }
        if (viewType == ITEM_TYPE_CONTENT){
            itemView = LayoutInflater.from(mContext).inflate(R.layout.preview_content_view,parent,false);
            return  new ContentHolder(itemView);
        }
        if (viewType == ITEM_TYPE_BOTTOM){
            itemView = LayoutInflater.from(mContext).inflate(R.layout.preview_foot_view,parent,false);
            return new FootHolder(itemView);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        if (holder instanceof HeadViewHolder){
            List<reportViewBean.JibenxinxiBean> jList = reportList.get(0).getJibenxinxi();
            reportViewBean.JibenxinxiBean bean = jList.get(0);
            ((HeadViewHolder) holder).mainName.setText(bean.getReportname());
            ((HeadViewHolder) holder).jibenText.setText(mContext.getResources().getString(R.string.jiben_info));
            ((HeadViewHolder) holder).city.setText(areaName);

            if (bean.getRealstart()!=null){
                String[] time = bean.getRealstart().split("T");
                 ((HeadViewHolder) holder).time.setText(time[0]);
            }else{
                ((HeadViewHolder) holder).time.setText("------");
            }
            ((HeadViewHolder) holder).evaScore.setText(bean.getSscore()+"("+bean.getSlevel()+")");
            ((HeadViewHolder) holder).empName.setText("评估人："+bean.getEmpname());
            ((HeadViewHolder) holder).shopNum.setText("餐厅编号："+bean.getShopnum());
            ((HeadViewHolder) holder).shopName.setText("餐厅名称："+bean.getShopname());
           // ((HeadViewHolder) holder).lastScore.setText("上次评估成绩:"+bean.getLastscore());
            ((HeadViewHolder) holder).lastScore.setVisibility(View.GONE);
        }
        if (holder instanceof ContentHolder){

            final reportViewBean.ZhutiBean zhuti = zhutiList.get(position-1);
            if (position==1){ //标题显示
                ((ContentHolder) holder).eva_detail.setVisibility(View.VISIBLE);
                ((ContentHolder)holder).eva_detail.setText("评估概述");
            }else{
                ((ContentHolder) holder).eva_detail.setVisibility(View.GONE);
            }
           // ((ContentHolder)holder).myImg.setAdapter();
            //失分项与重复失分项,失分项进入
            if (zhuti.getShifoushifen()==1){
                if (chongFuKouFens!=null&&chongFuKouFens.size()>0){
                    boolean falg = false; //是否含有
                    for (ChongFuKouFen ck:chongFuKouFens){
                        if (ck.getRrid()==zhuti.getRowId()){
                            falg = true;
                            ((ContentHolder) holder).islostItem.setVisibility(View.VISIBLE);
                            ((ContentHolder) holder).islostItem.setText("重复失分项");
                            ((ContentHolder) holder).islostItem.setBackgroundColor(mContext.getResources().getColor(R.color.repeat_item_color));
                            break;
                        }
                    }
                    if (!falg){
                        ((ContentHolder) holder).islostItem.setVisibility(View.VISIBLE);
                        ((ContentHolder) holder).islostItem.setText("失分项");
                        ((ContentHolder) holder).islostItem.setBackgroundColor(mContext.getResources().getColor(R.color.lost_item_color));
                    }
                }else{
                    ((ContentHolder) holder).islostItem.setVisibility(View.VISIBLE);
                    ((ContentHolder) holder).islostItem.setText("失分项");
                    ((ContentHolder) holder).islostItem.setBackgroundColor(mContext.getResources().getColor(R.color.lost_item_color));
                }
            }else{
                ((ContentHolder) holder).islostItem.setVisibility(View.GONE);
            }


            ((ContentHolder)holder).majorName.setText(zhuti.getDaxiangming()+calLostByMajorName(zhuti.getDaxiangming()));
            ((ContentHolder) holder).majorName.setVisibility(View.VISIBLE);
            Log.e("positionTitle",zhuti.getDaxiangming()+calLostByMajorName(zhuti.getDaxiangming()));
            Log.e("==out_position==",position+"");
            //是否显示大项名称
            if (position>=2){
                Log.e("==nei_position==",position+"");
                reportViewBean.ZhutiBean last = zhutiList.get(position-2);
                if (last.getDaxiangming().equals(zhuti.getDaxiangming())){
                    ((ContentHolder) holder).majorName.setVisibility(View.GONE);
                }else{
                    ((ContentHolder) holder).majorName.setVisibility(View.VISIBLE);
                }
            }
            //小项名称
            ((ContentHolder) holder).itemName.setText(zhuti.getXiaoxiangbianhao()+" "+zhuti.getXiaoxiangming());
            //小项描述
            ((ContentHolder) holder).itemDesc.setText("描述："+zhuti.getXiaoxiangmiaoshu());
            //得分
            ((ContentHolder) holder).itemScore.setText("得分： "+zhuti.getShijifenshu()+"(满分："+zhuti.getXiaoxiangmanfen()+")");
            //行动计划
            Log.e("zhuti",zhuti.isFbNeedFollow()+"=="+zhuti.getShijifenshu());
            if (zhuti.isFbNeedFollow()&&zhuti.getShifoushifen()==1){
                if (empList!=null&&empList.size()>0){
                    ((ContentHolder) holder).followLayout.setVisibility(View.VISIBLE);
                    Log.e("zhutiEmp",empList.get(0).getID()+"");
                    if (!TextUtils.isEmpty(zhuti.getFbPerson()+"")){
                        for (Employee emp:empList){
                            if (emp.getID() == zhuti.getFbPerson()){
                                ((ContentHolder) holder).dutyMen.setText("责任人："+emp.getFirstName());
                                ((ContentHolder) holder).endTime.setText("截至时间："+zhuti.getFbTime());
                            }
                        }
                    }
                }else{
                    ((ContentHolder) holder).followLayout.setVisibility(View.GONE);
                }
            }else{
                ((ContentHolder) holder).followLayout.setVisibility(View.GONE);
            }
            if (zhuti.getShifoushifen() == 1){
                ((ContentHolder) holder).indication.setBackgroundColor(mContext.getResources().getColor(R.color.left_itemColor));
            }else{
                ((ContentHolder) holder).indication.setBackgroundColor(mContext.getResources().getColor(R.color.divide_color2));
            }
            //失分描述
            if (!TextUtils.isEmpty(zhuti.getShifenmiaoshu())) {
                ((ContentHolder) holder).descLinear.setVisibility(View.VISIBLE);
                ((ContentHolder)holder).desc.setText(zhuti.getShifenmiaoshu());
                ((ContentHolder) holder).delDesc.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            tempLostRR rr = db.selector(tempLostRR.class).where("schId","=",zhuti.getSchId())
                                    .and("rRowId","=",zhuti.getRowId()).findFirst();
                            rr.setDescStr("");
                            db.saveOrUpdate(rr);
                            zhuti.setShifenmiaoshu("");
                            notifyDataSetChanged();
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }else{
                ((ContentHolder) holder).descLinear.setVisibility(View.GONE);
            }

            final List<String> dataList = new ArrayList<>();
            if (zhuti.getVideoList()!=null&&zhuti.getVideoList().size()>0){
                dataList.addAll(zhuti.getVideoList());
            }
            if (zhuti.getJpgList()!=null&&zhuti.getJpgList().size()>0){
                dataList.addAll(zhuti.getJpgList());
            }
            if (dataList.size()>0){
                ((ContentHolder) holder).photoLinear.setVisibility(View.VISIBLE);
                ImgGradeAdapter imgAdapter = new ImgGradeAdapter(mContext, dataList);
                ((ContentHolder) holder).myImg.setAdapter(imgAdapter);
                //查看详情
                ((ContentHolder) holder).myImg.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        String mediaStr = "";
                        for (int k=0;k<dataList.size();k++){
                            mediaStr += dataList.get(k).toString()+",";
                        }
                        String[] as = dataList.toString().split(",");
                        Log.e("as[0]",as[0]);


                        if (as[0].endsWith(".mp4")){ //视频加图片
                            if (position == 0){
                                mContext.startActivity(new Intent(mContext, PlayVideoActiviy.class)
                                        .putExtra("file_path",as[0].replace("[","")).putExtra("code_play",2));
                            }else{
                                String jpgstr = "";
                                for (int i=1;i<dataList.size();i++){
                                    jpgstr+= dataList.get(i) +",";
                                }
                                mContext.startActivity(new Intent(mContext, ImageViewPagerActivity.class)
                                        .putExtra("filepath", jpgstr).putExtra("position",position-1));
                            }
                        }
                        else if (as[0].endsWith("mp4]")){ //视频
                            mContext.startActivity(new Intent(mContext, PlayVideoActiviy.class)
                                    .putExtra("file_path",as[0].replace("[","")
                                            .replace("]","")).putExtra("code_play",2));
                        }else{
                            mContext.startActivity(new Intent(mContext, ImageViewPagerActivity.class)
                                    .putExtra("filepath", mediaStr).putExtra("position",position));
                        }

                    }
                });
                //长按删除
                ((ContentHolder) holder).myImg.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                    @Override
                    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                        if (dataList.get(position).endsWith(".mp4")&&position == 0){
                            //video
                            try {
                                tempLostRR rr = db.selector(tempLostRR.class).where("schId","=",zhuti.getSchId())
                                        .and("rRowId","=",zhuti.getRowId()).findFirst();
                                DelVidListItem(position,rr,dataList,zhuti);
                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                            return true;
                        }else{
                            // jpg
                            try {
                                tempLostRR rr = db.selector(tempLostRR.class).where("schId","=",zhuti.getSchId())
                                        .and("rRowId","=",zhuti.getRowId()).findFirst();
                                DelJpgListItem(position,rr,dataList,zhuti);
                            } catch (DbException e) {
                                e.printStackTrace();
                            }
                        }
                        return true;
                    }
                });

            }else{
                ((ContentHolder) holder).photoLinear.setVisibility(View.GONE);
            }
        }

        if (holder instanceof FootHolder){
            if (reportList.get(0).getQianming()!=null&&reportList.get(0).getQianming().length()>0){
                ((FootHolder) holder).signature.setVisibility(View.VISIBLE);
                Glide.with(mContext).load(reportList.get(0).getQianming()).thumbnail(0.5f).into(((FootHolder) holder).signature);
            }else{
                ((FootHolder) holder).signature.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public int getItemCount() {
        if (zhutiList!=null&&zhutiList.size()>0){
            return zhutiList.size()+HEAD_COUNT+FOOT_COUNT;
        }else{
            return HEAD_COUNT+FOOT_COUNT;
        }
    }

    @Override
    public int getItemViewType(int position) {

        if (zhutiList!=null&&zhutiList.size()>0){

            if (position == 0){
                return ITEM_TYPE_HEADER;
            }else if (position>=zhutiList.size()+1){
                return ITEM_TYPE_BOTTOM;
            } else{
                return ITEM_TYPE_CONTENT;
            }
        }else{
            if (position == 0) {
                return ITEM_TYPE_HEADER;
            }else{
                return ITEM_TYPE_BOTTOM;
            }
        }
    }

    class HeadViewHolder extends RecyclerView.ViewHolder {
        TextView jibenText;
        TextView evaScore;
        TextView city;
        TextView time;
        TextView empName;
        TextView shopNum;
        TextView lastScore;
        TextView shopName;
        TextView mainName;
        public HeadViewHolder(View itemView) {
            super(itemView);
            jibenText = itemView.findViewById(R.id.jibenText);
            evaScore = itemView.findViewById(R.id.evaScore);
            city = itemView.findViewById(R.id.city);
            time = itemView.findViewById(R.id.time);
            empName = itemView.findViewById(R.id.empName);
            shopNum = itemView.findViewById(R.id.shopNum);
            lastScore = itemView.findViewById(R.id.lastScore);
            shopName = itemView.findViewById(R.id.shopName);
            mainName = itemView.findViewById(R.id.mainName);
        }
    }
    class ContentHolder extends RecyclerView.ViewHolder {
        TextView eva_detail;
        TextView majorName;
        View indication;
        TextView islostItem;
        TextView itemName;
        TextView itemScore;
        TextView dutyMen;
        TextView endTime;
        RelativeLayout followLayout;
        TextView desc;
        GridView myImg;
        TextView delDesc;
        RelativeLayout descLinear;
        LinearLayout photoLinear;
        TextView itemDesc;

        public ContentHolder(View itemView) {
            super(itemView);
            eva_detail = itemView.findViewById(R.id.eva_detail);
            majorName = itemView.findViewById(R.id.majorName);
            desc = itemView.findViewById(R.id.desc);
            myImg = itemView.findViewById(R.id.myImg);
            indication = itemView.findViewById(R.id.indication);
            itemName = itemView.findViewById(R.id.itemName);
            islostItem = itemView.findViewById(R.id.islostItem);
            dutyMen = itemView.findViewById(R.id.dutyMen);
            itemScore = itemView.findViewById(R.id.itemScore);
            endTime = itemView.findViewById(R.id.endTime);
            followLayout = itemView.findViewById(R.id.followLayout);
            photoLinear = itemView.findViewById(R.id.photoLinear);
            descLinear = itemView.findViewById(R.id.descLinear);
            delDesc = itemView.findViewById(R.id.delDesc);
            itemDesc = itemView.findViewById(R.id.itemDesc);
        }
    }
    class FootHolder extends RecyclerView.ViewHolder {
        ImageView signature;
        public FootHolder(View itemView) {
            super(itemView);
            signature = itemView.findViewById(R.id.signature);
        }
    }


    private String calLostByMajorName(String name){
        int count = 0;
        for (reportViewBean.ZhutiBean zhutiBean:zhutiList){
            if (zhutiBean.getDaxiangming().equals(name)&&zhutiBean.getShifoushifen()==1){
                count++;
            }
        }
        if (count>0){
            return " ("+count+"项失分项)";
        }else{
            return "";
        }
    }


    private void DelVidListItem(final int position, final tempLostRR rr, final List<String> mediaList, final reportViewBean.ZhutiBean zhuti){
        MaterialDialogUtils.showMaterialDialog(mContext, "是否删除视频", "确定", "取消", true,false,
                new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
                mediaList.remove(position);
                rr.setVideoStr("");
                zhuti.setVideoList(null);
                try {
                    db.saveOrUpdate(rr);
                    notifyDataSetChanged();
                } catch (DbException e) {
                    e.printStackTrace();
                }

            }
        }, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
            }
        });
    }
    private void DelJpgListItem(final int position, final tempLostRR rr, final List<String> mediaList, final reportViewBean.ZhutiBean zhuti){
        MaterialDialogUtils.showMaterialDialog(mContext, "是否删除图片", "确定", "取消", true,false,
                new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

                        if (mediaList.get(0).endsWith(".mp4")){
                            zhuti.getJpgList().remove(position-1);

                        }else{
                            zhuti.getJpgList().remove(position);
                        }
                        String newAllvideoFile="";
                        for (int i=0;i<zhuti.getJpgList().size();i++){
                            newAllvideoFile+=zhuti.getJpgList().get(i)+",";
                        }
                        rr.setJpgStr(newAllvideoFile);
                        try {
                            db.saveOrUpdate(rr);
                            notifyDataSetChanged();
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                }, new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                    }
                });
    }




}
